// mycomponent/temp/qrcode/qrcode.js
var app = getApp();
var posterBehavior = require('../../../poster/poster.js');
Component({
  behaviors: [posterBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    store_alone_temp: {
      // 门店独立判断
      type: null,
    },
    activity_id:{
      type:null
    },
    new_poster_id:{
      type:null
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    poster_id: 0,
    step: 1,
    is_new: 0
  },
  ready() {
    //	this.getPosterPic();
  },
  /**
   * 组件的方法列表
   */
  methods: {
    async initPosterData(){
      // 海报中心生成海报
      let posterSize = await this.getMyCanvasMessage(640, 1008);
      this.setData({
        canvasWidth: posterSize.width,
        canvasHeight: posterSize.height
      });
      // 海报中心 默认前端生成
      if(this.data.defaultImg){
        // 有记录
        this.setData({
          loading: 100,
          poster: this.data.defaultImg,
        });
        this.triggerEvent("finishDefaultImg",this.data.poster);
      }else{
        let poster_data = this.data.posterData;
        let jsonarr = {
          background:poster_data.background.src,
          type:poster_data.background.type,
          style_data:poster_data.poster_data,
        }
        console.log(jsonarr,'jsonarr')
        this.startDrawCanvas(posterSize, jsonarr);
      }
    },
    async getPosterPic() {
      let posterSize = await this.getMyCanvasMessage(640, 1008);

      this.setData({
        canvasWidth: posterSize.width,
        canvasHeight: posterSize.height
      });

      let urlStr = app.getNetAddresss("member.qrcode.get-poster");
      if (this.data.store_alone_temp == 1) {
        urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.qrcode.get-poster");
      }
      if(this.data.poster_id) {
        urlStr = urlStr+'&poster_id='+this.data.poster_id;
      }
      if(this.data.new_poster_id && this.data.activity_id ){
        urlStr = app.getNetAddresss("plugin.crowdfunding.frontend.activity-member.promotePoster");
        urlStr = urlStr+'&new_poster_id='+this.data.new_poster_id +'&activity_member_id='+this.data.activity_id;
      }
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result != 1) {
            return;
          }
          if(this.data.new_poster_id && this.data.activity_id ){
            if(res.data.new){
              let jsonarr = {
                background:res.data.background.src,
                type:res.data.background.type,
                style_data:res.data.style_data,
              }
              this.startDrawCanvas(posterSize, jsonarr);
            }else{
              this.setData({
                loading: 100,
                poster: res.data,
              });
            }
            
            return
          }
          if (res.data.center_show == 0) {
            this.setData({
              loading: 100,
              poster: res.data.image_url,
            });
          } else if (res.data.center_show == 1) {
            this.data.poster_id = res.data.id;
            if (res.data.new && res.data.new == true) {
              this.data.is_new = 1;
              this.startDrawCanvas(posterSize, res.data);
            } else {
              this.startOldDrawCanvas(posterSize, res.data);
            }

          } else if (res.data.center_show == 2) {
            this.getPosterTp2();
          }

        }
      });
    },
    getPosterTp2() {
      let that = this;
      let urlStr = app.getNetAddresss("member.poster");
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.image_url == "" || res.data.image_url == null) {
              wx.showToast({
                title: '请稍等' + res.data.image_url,
                icon: 'none',
                duration: 2000
              });
              setTimeout(() => {
                this.getPosterTp2();
              }, 500);

            } else if (res.data.image_url != "") {
              setTimeout(() => {
                that.setData({
                  poster: res.data.image_url,
                });
              }, 2000);
            }

          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
          }

        },
        fail: function (res) {
          if (this.data.timer) {
            clearInterval(this.data.timer);
          }
          wx.hideLoading({});
        }
      });
    },
    async startDrawCanvas(posterSize, posterData) {
      if(this.data.plugin_name == 'posterCenter'){ 
        wx.showLoading({
          title: '海报加载中',
        }) 
      }
      const ctx = wx.createCanvasContext('myCanvas', this);
      ctx.save();
      if(posterData.type == 'color'){
        ctx.setFillStyle(posterData.background);
      }else{
        ctx.setFillStyle('#fff');
      }
      this.drawRoundRectPath(ctx, posterSize.width, posterSize.height, 30);
      ctx.fillRect(0, 0, posterSize.width, posterSize.height);
      //ctx.draw();
      if(posterData.type != 'color'){
        //下载背景
        let bgImg = await this.downImage({src:posterData.background});
        //绘制背景图片
        this.setProportion(posterSize, bgImg);
        this.drawCanvasImage(ctx, {
          left: 0,
          top: 0,
          width: bgImg.width / this.data.step,
          height: bgImg.height / this.data.step,
          img: bgImg.img
        });
      }
      this.setData({
        loading: 10
      });

      //绘制其他内容
      let otherData = posterData.style_data;
      for (let i = 0; i < otherData.length; i++) {

        let item = otherData[i];
        //绘制昵称
        if (item.type == "nickname" || item.type == "invite" || item.type == "text" || item.type == "mid") {
          this.drawCanvasText(ctx, item);
        } else if (item.type == "img" || item.type == "head" || item.type == "qr" || item.type == "shopqr" || item.type == "logo") { // 代表后台有图片
          // //下载和读取图片
          if (item.src) {
            let file = await this.downImage(item);
            item.img = file.img;
            this.drawCanvasImage(ctx, item);
          }
        }
        let loading = parseInt((80 / otherData.length) * (i + 1));
        this.setData({
          loading: loading + 10
        });
      }
      ctx.draw(false, setTimeout(async () => {
        let img = await this.toimage('myCanvas', posterSize);
        this.setData({
          loading: 100,
          poster: img,
        });
        if(this.data.plugin_name == 'posterCenter'){
          // console.log("已经生成海报")
          wx.hideLoading({
            success: (res) => {},
          })
          this.triggerEvent("finishDefaultImg",this.data.poster)
          return
        }else{
          this.upQrcodeImg(img);
        }
      }, 1000));

    },
    //工具
    //开始绘制,兼容旧版本

    async startOldDrawCanvas(posterSize, posterData) {
      const ctx = wx.createCanvasContext('myCanvas', this);
      ctx.save();
      this.drawRoundRectPath(ctx, posterSize.width, posterSize.height, 30);

      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, posterSize.width, posterSize.height);
      //ctx.draw();

      //下载背景
      let bgImg = await this.downImage({src:posterData.background});
      // let bgImg = await this.readDownPicInfo(posterData.background);
      //绘制背景图片
      this.setProportion(posterSize, bgImg);
      this.drawCanvasImage(ctx, {
        left: 0,
        top: 0,
        width: bgImg.width / this.data.step,
        height: bgImg.height / this.data.step,
        img: bgImg.img
      });
      this.setData({
        loading: 10
      });

      //绘制其他内容
      let otherData = posterData.style_data;
      for (let i = 0; i < otherData.length; i++) {

        let item = otherData[i];
        //绘制昵称
        if (item.type == "nickname") {
          this.drawCanvasText(ctx, item);
        } else if (item.type == "img" || item.type == "head") { // 代表后台有图片
          // //下载和读取图片
          if (item.src) {
            let file = await this.downImage(item);
            item.img = file.img;
            this.drawCanvasImage(ctx, item);
          }
        } else if (item.type == "qr_shop" || item.type == "qr_app_share") { //需要自己将链接生成二维码
          let img = await this.getQRCodeUrl(item);
          item.img = img;
          this.drawCanvasImage(ctx, item);
        }
        let loading = parseInt((80 / otherData.length) * (i + 1));
        this.setData({
          loading: loading + 10
        });
      }
      ctx.draw(false, setTimeout(async () => {
        let img = await this.toimage('myCanvas', posterSize);
        this.setData({
          loading: 100,
          poster: img,
        });
        this.upQrcodeImg(img);
      }, 1000));

    },

    upQrcodeImg(imgFile) {
      let wx_token = wx.getStorageSync('wx_token');
      let session = wx.getStorageSync('session');
      let urlStr = app.getNetAddresss('member.qrcode.uploadLocal');
      urlStr += '&poster_id=' + this.data.poster_id + '&is_new=' + this.data.is_new;
      urlStr += '&3rd_session=' + session;
      wx.uploadFile({
        url: urlStr,
        filePath: imgFile,
        name: 'file',
        formData: {
          // 和服务器约定的token, 一般也可以放在header中
          '_wx_token': wx.getStorageSync('wx_token'),
          'ingress': 0
        },
        header: {
          "Content-Type": "multipart/form-data",
          Cookie: "PHPSESSID=" + wx_token,
        },
        success: (res) => {

          let data = JSON.parse(res.data);
          if (data.result == 1) {
            //data.data.img_url
            this.addPosterRecord(data.data.img_url);
          }
        },
        fail: function (e) {
        }
      });
    },
    addPosterRecord(img_url) {
      var urlStr = app.getNetAddresss("member.qrcode.poster-record");
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        data: {
          image: img_url,
          poster_id: this.data.poster_id,
          is_new: this.data.is_new
        },
        success: (resdata) => {

        }
      });
    }
  }
});